<?php
class Admin_ArticleController extends Admin_BaseController {

	public function getArticles() {
		$BGs = Encyclopedie::all();
		return View::make('admin.article.articles', compact("BGs"));
	}

	public function newArticle() {
		$BGs = Encyclopedie::all();
		$bgSelect = array();
		foreach($BGs as $bg){
			$bgSelect[$bg->article_id] = $bg->titre;
		}
		return View::make('admin.article.add-article', compact('bgSelect'));
	}

	public function postAddArticle(){
		$rules = array(
			'titre' => 'required|between:1,255',
			'parent' => 'required',  // required|numeric|exists??
			'layout' => 'required',
			'url'   => 'required|between:1,255',
			'texte' => 'required',
		);

		$validator = Validator::make(Input::all(),$rules);

		if($validator->fails()) 
		{
			return Redirect::back()->withInput()->withErrors($validator);
		} 
		else 
		{
			$bg = new Encyclopedie;
			$bg->parent_id = Input::get('parent');
			$bg->titre = Input::get('titre');
			$bg->texte = Input::get('texte');
			$bg->layout = Input::get('layout');
			$bg->displayChildren = Input::get('displaychildren') ? : 0;
			$bg->url = Input::get('url');
			$bg->titre = Input::get('titre');
			$bg->save();
			return Redirect::route('admin-articles');
		}
	}

	public function postEditArticle($id = null){
		$rules = array(
			'titre' => 'required|between:1,255',
			'parent' => 'required', // required|numeric|exists??
			'layout' => 'required',
			'url'   => 'required|between:1,255',
			'texte' => 'required',
		);

		$validator = Validator::make(Input::all(),$rules);

		if($validator->fails()) {
			dd($validator);
			return Redirect::back()->withInput()->withErrors($validator);
		} else {
			$bg = Encyclopedie::find($id);
			$bg->parent_id = Input::get('parent');
			$bg->titre = Input::get('titre');
			$bg->texte = Input::get('texte');
			$bg->layout = Input::get('layout');
			$bg->displayChildren = (Input::get('displaychildren'))?:0;
			$bg->url = Input::get('url');
			$bg->save();
			return Redirect::route('admin-articles');
		}
	}

	public function editArticle($id){
		$BGs = Encyclopedie::all();
		$bg = Encyclopedie::find($id);
		$bgSelect = array();
		foreach($BGs as $bgitem){
			$bgSelect[$bgitem->article_id] = $bgitem->titre;
		}
		return View::make('admin.article.edit-article', compact('bg','bgSelect'));
	}

	public function deleteArticle($id = null){
		Encyclopedie::destroy($id);
		return Redirect::route("admin-articles");
	}
}
